package com.kfm.listener;

import com.kfm.util.Constant;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

// 监听session属性的变化
@WebListener
public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener {

    // 属性新增触发
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        System.out.println("session新增了" + event.getName() + "属性-->" + event.getValue());
        // 当新增的是登录用户信息的时候，才应该 + 1
        if (Constant.LOGIN_USER_KEY.equals(event.getName())) { // 新增的是登录信息属性
            ServletContext servletContext = event.getSession().getServletContext();
//            List<String> attribute = (List<String>) servletContext.getAttribute(Constant.ONLINE_KEY);
//            attribute.add((String)event.getValue());
            ConcurrentHashMap<String, HttpSession> map = (ConcurrentHashMap<String, HttpSession>) servletContext.getAttribute(Constant.ONLINE_KEY);
            HttpSession session = event.getSession();
            map.put(session.getId(), session);
//            servletContext.setAttribute(Constant.ONLINE_KEY, attribute);
        }
    }

    // 属性删除触发
    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        System.out.println("session删除了" + event.getName() + "属性");
        if (Constant.LOGIN_USER_KEY.equals(event.getName())) {
            ServletContext servletContext = event.getSession().getServletContext();
            List<String> attribute = (List<String>) servletContext.getAttribute(Constant.ONLINE_KEY);
            attribute.remove((String)event.getValue());
//            servletContext.setAttribute(Constant.ONLINE_KEY, attribute);
        }
    }

    // 属性修改触发
    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        System.out.println("session修改了" + event.getName() + "属性-->" + event.getValue());
    }
}
